package com.ruoyi.system.service.impl;

import com.ruoyi.system.domain.BPicture_af;
import com.ruoyi.system.mapper.BPicture_afMapper;
import com.ruoyi.system.service.IBPicture_afService;
import com.ruoyi.system.service.IBPicture_afService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 电子图片Service业务层处理
 *
 * @author guangpipi
 * @date 2023-09-21
 */
@Service
public class BPicture_afServiceImpl implements IBPicture_afService
{
    @Autowired
    private BPicture_afMapper bEPictureMapper;

    /**
     * 查询电子图片
     *
     * @param id 电子图片主键
     * @return 电子图片
     */
    @Override
    public BPicture_af selectBEPictureById(String id)
    {
        return bEPictureMapper.selectBEPictureById(id);
    }

    /**
     * 查询电子图片列表
     *
     * @param bEPicture 电子图片
     * @return 电子图片
     */
    @Override
    public List<BPicture_af> selectBEPictureList(BPicture_af bEPicture)
    {
        return bEPictureMapper.selectBEPictureList(bEPicture);
    }

    /**
     *  获取图片
     *  @param id 文件信息主键
     *  @return pdf
     */
//    public ResponseEntity<byte[]> getPic(String id){
//        try{
//            BPicture_af bePicture = bEPictureMapper.selectBEPictureById(id);
//            String path = changeType(bePicture.getFileDirectory());
//            File picByte = new File(path);
//            byte[] picBytes = Files.readAllBytes(picByte.toPath());
//            this.deletePic(path);
//            return ResponseEntity.ok().header("Content-Type","application/jpg").body(picBytes);
//        }catch (IOException e){
//            e.printStackTrace();
//            return ResponseEntity.badRequest().build();
//        }
//    }

    public ResponseEntity<byte[]> getPic(String id){
        try{
            BPicture_af bePicture = bEPictureMapper.selectBEPictureById(id);

            BufferedImage tiffImage= ImageIO.read(new File(bePicture.getFileDirectory()));
            ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
            ImageIO.write(tiffImage, "jpg", jpegOutputStream);
            byte[] picBytes = jpegOutputStream.toByteArray();

            return ResponseEntity.ok().header("Content-Type","application/jpg").body(picBytes);
        }catch (IOException e){
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }



    /**
     *  下载图片
     *  @param id 文件信息主键
     *  @return pdf
     */
    public ResponseEntity<byte[]> downloadPic(String id){
        try{
            BPicture_af bePicture = bEPictureMapper.selectBEPictureById(id);
            File picByte = new File(bePicture.getFileDirectory());
            byte[] picBytes = Files.readAllBytes(picByte.toPath());
            return ResponseEntity.ok().header("Content-Type","application/tif").body(picBytes);
        }catch (IOException e){
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 删除图片
     */
    public void deletePic(String path){
        File file = new File(path);
        file.delete();
    }


    /**
     *  更换图片格式
     */
    public String changeType(String path){
        // 获取字符串除了最后三个字符的部分
        String baseName = path.substring(0, path.length() - 3);
        baseName = baseName + "jpg";
        try{
            // 读取.tif格式的图像
            File tifFile = new File(path);
            BufferedImage tifImage = ImageIO.read(tifFile);

            // 创建.jpg格式的文件
            File jpgFile = new File(baseName);

            // 写入.jpg格式的图像
            ImageIO.write(tifImage, "jpg", jpgFile);


        }catch (IOException e){
            e.printStackTrace();
        }
        return baseName;
    }

    /**
     * 获取文件类型
     */
    public String getpictype(String picId){
        String id = picId.replace("++", "/");
        BPicture_af bePicture = bEPictureMapper.selectBEPictureById(id);
        return bePicture.getType();
    }

    /**
     *
     * 预览图片
     *
     */
    public ResponseEntity<byte[]> getFile(String picId){
        String id = picId.replace("++", "/");
        try{
            BPicture_af bePicture = bEPictureMapper.selectBEPictureById(id);
            File picByte = new File(bePicture.getFileDirectory());
            byte[] picBytes = Files.readAllBytes(picByte.toPath());
            return ResponseEntity.ok().header("Content-Type","application/tif").body(picBytes);
        }catch (IOException e){
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     *  批量下载
     */
    public ResponseEntity<byte[]> downloadMore(String[] ids){
        String filePath = "D:\\temporaryFolder";
        String zipPath = "D:\\fileZip.zip";
        try{
            File folder = new File(filePath);
            if(!folder.exists()){
                folder.mkdirs();
            }

            for(String picId : ids){
                String id = picId.replace("++", "/");
                BPicture_af bePicture = bEPictureMapper.selectBEPictureById(id);
                String oldPath = bePicture.getFileDirectory();
                String targetPath = "D:\\temporaryFolder\\" + bePicture.getPicName() + "." + bePicture.getType();
                File oldFile = new File(oldPath);
                File newFile = new File(targetPath);
                Files.copy(oldFile.toPath(),newFile.toPath());
            }

            zipFolder(filePath,zipPath);
            byte[] zipFileData = readZipFile(zipPath);

            File folderToDelete = new File(filePath);
            deleteFolderAndContents(folderToDelete);
            File zipFileToDelete = new File(zipPath);
            deleteFile(zipFileToDelete);
            return ResponseEntity.ok().header("Content-Type","application/zip").body(zipFileData);
        } catch (IOException e){
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }

    public void zipFolder(String folderPath, String zipFileName) throws IOException {
        File folder = new File(folderPath);
        if (folder.exists() && folder.isDirectory()) {
            try (FileOutputStream fos = new FileOutputStream(zipFileName);
                 ZipOutputStream zos = new ZipOutputStream(fos)) {
                for (File file : folder.listFiles()) {
                    if (file.isFile()) {
                        ZipEntry zipEntry = new ZipEntry(file.getName());
                        zos.putNextEntry(zipEntry);
                        try (FileInputStream fis = new FileInputStream(file)) {
                            byte[] buffer = new byte[1024];
                            int length;
                            while ((length = fis.read(buffer)) > 0) {
                                zos.write(buffer, 0, length);
                            }
                        }
                        zos.closeEntry();
                    }
                }
            }
        }
    }

    private byte[] readZipFile(String zipFileName) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileInputStream fis = new FileInputStream(zipFileName);
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = fis.read(buffer)) != -1) {
            baos.write(buffer, 0, bytesRead);
        }
        fis.close();
        return baos.toByteArray();
    }

    private static boolean deleteFolderAndContents(File folder) {
        if (folder.exists()) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        if (!deleteFolderAndContents(file)) {
                            return false;
                        }
                    } else {
                        if (!deleteFile(file)) {
                            return false;
                        }
                    }
                }
            }
            return folder.delete();
        }
        return false;
    }

    private static boolean deleteFile(File file) {
        if (file.exists()) {
            return file.delete();
        }
        return false;
    }
    /**
     * 新增电子图片
     *
     * @param bEPicture 电子图片
     * @return 结果
     */
    @Override
    public int insertBEPicture(BPicture_af bEPicture)
    {
        return bEPictureMapper.insertBEPicture(bEPicture);
    }

    /**
     * 修改电子图片
     *
     * @param bEPicture 电子图片
     * @return 结果
     */
    @Override
    public int updateBEPicture(BPicture_af bEPicture)
    {
        return bEPictureMapper.updateBEPicture(bEPicture);
    }

    /**
     * 批量删除电子图片
     *
     * @param ids 需要删除的电子图片主键
     * @return 结果
     */
    @Override
    public int deleteBEPictureByIds(String[] ids)
    {
        return bEPictureMapper.deleteBEPictureByIds(ids);
    }

    /**
     * 删除电子图片信息
     *
     * @param id 电子图片主键
     * @return 结果
     */
    @Override
    public int deleteBEPictureById(String id)
    {
        return bEPictureMapper.deleteBEPictureById(id);
    }
}
